package com.sz.ruichar.service.beans;

import com.sz.ruichar.entity.beans.TScoreGoods;
import com.sz.ruichar.entity.beans.TScoreGoodsLog;
import com.sz.ruichar.entity.beans.TUserScore;
import com.sz.ruichar.entity.beans.TUserScoreLog;
import com.sz.ruichar.entity.enums.ScoreAddTypeEnum;
import com.sz.ruichar.entity.enums.ScoreLogTypeEnum;
import com.sz.ruichar.entity.model.constant.MsgException;
import com.sz.ruichar.service.entity.model.result.ResultData;
import com.sz.ruichar.service.mapper.beans.TScoreGoodsMapper;
import com.sz.ruichar.service.mapper.beans.TUserScoreMapper;
import com.sz.ruichar.interfs.beans.ITScoreGoodsService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 积分兑换的商品 服务实现类
 * </p>
 *
 * @author 5beans
 * @since 2017-12-28
 */
@Service
public class TScoreGoodsServiceImpl extends ServiceImpl<TScoreGoodsMapper, TScoreGoods> implements ITScoreGoodsService {

	@Autowired private TScoreGoodsMapper scoreGoodsMapper;
	@Autowired private TUserScoreMapper userScoreMapper;
	
	@Override
	@Transactional
	public ResultData rechangeGood(Map<String, Object> param) throws MsgException {
		String openid = null == param.get("openid")?"":param.get("openid").toString();
		String goodid = null == param.get("goodid")?"":param.get("goodid").toString();
		TScoreGoods good = scoreGoodsMapper.selectById(goodid);
		TUserScore score = new TUserScore();
		score.setOpenid(openid);
		score = userScoreMapper.selectOne(score);
		if(null != good && null != good.getStoreNm() && good.getStoreNm()>0){
			if(null != score && null != score.getScore()){
				if(score.getScore().intValue() >= good.getCostScore().intValue()){
					//扣取积分
					score.setScore(score.getScore()-good.getCostScore());
					score.updateById();
					//库存减1
					if((good.getStoreNm().intValue() - 1) >=0 ){
						good.setStoreNm(good.getStoreNm() - 1);
						good.updateById();
					}else{
						throw new MsgException("库存不足");
					}
					//增加兑换记录
					TScoreGoodsLog log = new TScoreGoodsLog();
					log.setOpenid(openid);
					log.setGoodNo(good.getGoodsNo());
					log.insert();
					//积分变化日志
					TUserScoreLog scoreLog = new TUserScoreLog();
					scoreLog.setOpenid(openid);
					scoreLog.setScore(good.getCostScore());
					scoreLog.setType(ScoreLogTypeEnum.exchange.getCode());
					scoreLog.setAddType(ScoreAddTypeEnum.subtract.getCode());
					scoreLog.insert();
				}else{
					throw new MsgException("积分不足");
				}
			}else{
				throw new MsgException("无积分信息");
			}
		}else{
			throw new MsgException("无该商品信息，或库存不足");
		}
		return ResultData.success();
	}
	
}
